/*
 * gpio.v
 *
 * Copyright 2024 dh33ex <dh33ex@riseup.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA or visit <http://www.gnu.org/licenses/>.
 *
 *
 */

module gpio(
    input                i_rst,
    input                i_clk,

    input       [31:0]   i_addr,
    input       [31:0]   i_wd,
    input                i_we,

    input       [31:0]   i_gpio,
    output      [31:0]   o_gpio,
    output      [31:0]   o_rd
);

    /* GPIO */
    reg [31:0]  GPIO[284:287];

    always @(posedge i_clk) begin
        if (i_we && i_addr >= 32'h470 && i_addr < 32'h47C) begin
            GPIO[i_addr[31:2]] <= i_wd;
        end

        GPIO[285] <= i_gpio;
    end

    /* PWM */
    wire [4:0]   pin_1;
    wire         en_1;
    wire [15:6]  duty_1;
    wire [20:16] pin_2;
    wire         en_2;
    wire [31:22] duty_2;

    assign pin_1 = GPIO[286][4:0];
    assign en_1 = GPIO[286][5];
    assign duty_1 = GPIO[286][15:6];
    assign pin_2 = GPIO[286][20:16];
    assign en_2 = GPIO[286][21];
    assign duty_2 = GPIO[286][31:22];

    pwm pwm_1(
        .i_rst(i_rst),
        .i_clk(i_clk),
        .i_duty(duty_1),
        .o_pwm(o_pwm_1)
    );
    pwm pwm_2(
        .i_rst(i_rst),
        .i_clk(i_clk),
        .i_duty(duty_2),
        .o_pwm(o_pwm_2)
    );

    /* output GPIO by register value of pwm */
    genvar i;
    generate
    for (i = 0; i < 32; i = i + 1)
        assign o_gpio[i] = ((en_1 == 1'b1 && pin_1 == i) ? o_pwm_1 : ((en_2 == 1'b1 && pin_2 == i) ? o_pwm_2 : GPIO[284][i]));
    endgenerate

    /* output gpio reg */
    assign o_rd = GPIO[i_addr[31:2]];

endmodule


module pwm(
    input                i_rst,
    input                i_clk,
    input       [9:0]    i_duty,
    output reg           o_pwm
);
    reg [9:0] counter;

    always @(posedge i_clk) begin
        if (i_rst) begin
            o_pwm   <= 1'b0;
            counter <= 8'h00;
        end else begin
            counter <= counter + 1;
            if (counter > i_duty) begin
                o_pwm <= 1'b0;
            end else begin
                o_pwm <= 1'b1;
            end
        end
    end

endmodule
